package ATM.dao.impl;

import ATM.bean.UserBean;
import ATM.dao.IUserDAO;

import java.sql.SQLException;

public class UserDAOImpl extends BaseDAO implements IUserDAO {

    /**
     * 登陆
     *
     * @param username 账号
     * @param pwd      密码
     * @return 用户对象，如果登陆失败，返回 null
     */
    @Override
    public UserBean login(String username, String pwd) {
        this.setConnection();
        UserBean userBean = new UserBean();
        try {
            ps = con.prepareStatement("select *from t_users where pk_username=? and u_password=?");
            ps.setObject(1, username);
            ps.setObject(2, pwd);
            rs = ps.executeQuery();
            if (rs.next()) {
                userBean.setUsername(rs.getString("pk_username"));
                userBean.setPassword(rs.getString("u_password"));
                userBean.setMoney(rs.getInt("u_money"));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            this.closeConnection();
        }
        return userBean;
    }

    /**
     * 通过账号修改余额
     *
     * @param username
     * @param money
     */
    @Override
    public void update(String username, Integer money) {
        this.setConnection();
        try {
            ps = con.prepareStatement("update t_users set u_money=? where pk_username=?");
            ps.setObject(1, money);
            ps.setObject(2, username);
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            this.closeConnection();
        }
    }

    /**
     * 通过账号获取用户
     *
     * @param username 账号
     * @return
     */
    @Override
    public UserBean getUserByName(String username) {
        this.setConnection();
        UserBean userBean = new UserBean();
        try {
            ps = con.prepareStatement("select *from t_users where pk_username=?");
            ps.setObject(1, username);
            rs=ps.executeQuery();
            if (rs.next()) {
                userBean.setUsername(rs.getString("pk_username"));
                userBean.setPassword(rs.getString("u_password"));
                userBean.setMoney(rs.getInt("u_money"));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            this.closeConnection();
        }
        return userBean;
    }


}
